/**
 * Copyright © 2011 looty - Textoo
 * @link http://www.textoo.org
 * @link http://code.google.com/p/textoo/
 * @author lab9 - Bertrand Larrieu
 * @mail lab9.fr@gmail.com
 * @version 2.0
 */

package org.looty.core.textoo.render 
{
	import flash.display.*;
	import flash.geom.*;
	import flash.text.*;
	import org.looty.core.textoo.format.*;
	import org.looty.textoo.render.*;

	public class SplittedTextfieldRenderer extends AbstractTextooRenderer implements ITextooRenderer
	{
		
		private var _textField			:TextField;
		
		public function SplittedTextfieldRenderer() 
		{
			super(3);
			
			_textField = createTextField();
		}
		
		
		override protected function applyProperties(textField:TextField, props:TextooProps):void 
		{
			_textField.text = "";
			super.applyProperties(textField, props);
		}
		
		public function render(props:TextooProps):RenderData 
		{
			applyProperties(_textField, props);
			
			var displayObjects:Vector.<DisplayObject> = new Vector.<DisplayObject>();
			var letters:Vector.<ILetter> = new Vector.<ILetter>(props.length);
			var i:int;
			var char:String;
			var bounds:Rectangle;
			var letter:TextFieldLetter;
			var textFormat:TextFormat;
			var definition:Class = props.textFieldLetterClass || TextFieldLetter;
			
			all:for each (var textRun:TextRun in _textField.getTextRuns())
			{
				
				textFormat = textRun.textFormat;
				
				run:for (i = textRun.beginIndex; i < textRun.endIndex; ++i)
				{
					if (i >= props.length) break all;
					
					char = props.text.charAt(i);
					if (/\s/.test(char)) continue run;
					
					bounds = _textField.getCharBoundaries(i);
					
					if (bounds == null) continue run;
					
					letter = new definition();
					letter.construct(char, bounds, props, textFormat);					
					
					displayObjects[displayObjects.length] = letter;
					letters[i] = letter;					
				}
			}
			
			_textField.text = "";
			
			return new RenderData(displayObjects, letters, null);
		}
		
	}

}